import React from 'react';
import { Upload,Modal ,message,Button,notification,Alert,Row,Col} from 'antd';
import { UploadOutlined ,DeleteOutlined,PlayCircleOutlined,PauseCircleOutlined , DownloadOutlined,SwapOutlined,ExclamationCircleOutlined} from '@ant-design/icons';
import http from 'axios'
import OSS from 'ali-oss'
import '../index.scss'
import {replaceAudio} from 'api/index'
import { connect } from 'react-redux'
const {confirm} = Modal

class App extends React.Component {
  state = {
    fileList: this.props.audio?[{url:this.props.audio,status: 'done'}]:[],
    isPlay:false,
    checkVisible:false,
    audioUrl:'',
    newAudioUrl:'',
    disabled:this.props.disabled
  };

  componentWillReceiveProps(nextProps){


    let self = this;
    self.setState({
      disabled:nextProps.disabled
    }) 

    if(nextProps.audio&&!nextProps.id){
      self.setState({ fileList:nextProps.audio?[{url:nextProps.audio,status: 'done'}]:[] });
      return
    }

    self.setState({ fileList:nextProps.value?[{url:nextProps.value,status: 'done'}]:[] });
    }

  audio = React.createRef();

  handleChange = ({ fileList }) => {
    this.setState({ fileList:fileList.filter(i=>i.status==='done') });
  }

  handleMove = (file) =>{
    this.setState({
      fileList:[...this.state.fileList].filter(i=>i.status==='done')
    })
  }

  customRequest = (file) => {
    var suffix = file.file.name.substr(file.file.name.indexOf('.')) // 获取文件后缀名
    var filename = new Date().getTime() + suffix // 为文件命名

    const token =  window.location.href.indexOf('/prd') === -1 ?localStorage.getItem('token-llx-test'):localStorage.getItem('token-llx')
    http({
      method: 'post',
      url:  window.location.href.indexOf('/prd')===-1?'http://139.224.81.105:19999/qia-cloud-filesystem/OSS/companies/getStsToken':'http://139.224.81.105:9999/qia-cloud-filesystem/OSS/companies/getStsToken',
      headers:  { 'Authorization': 'Bearer ' + token}
    }).then(res => {
      const fileData = res
      var bucket = 'middle-file'
      var region = 'oss-cn-shanghai'
      var type = ''
      const client = new OSS({
        region,
        accessKeyId: fileData.accessKeyId,
        accessKeySecret: fileData.accessKeySecret,
        stsToken: fileData.stsToken,
        bucket
      })
      type = 'audio'
      console.log(client);
      client.multipartUpload(type + '/' + filename, file.file).then((result) => {
        var url = result.res.requestUrls[0]
        var length = url.lastIndexOf('?')
        var getUrl = length > 0 ? url.substr(0, length) : url // 文件最终路径

        this.setState({
          fileList:[...this.state.fileList,{url:getUrl,status: 'done'}].filter(i=>i.status==='done')
        })

        this.props.setAudio(getUrl)
      }).catch(function(err) {
        notification.error({
          description:'上传失败',
          duration:1
        })
      })
  }).catch(err=>{
    notification.error({
      description:'上传失败',
      duration:1
    })
  })
  }

  customRequestReplace = (file) => {
    var suffix = file.file.name.substr(file.file.name.indexOf('.')) // 获取文件后缀名
    var filename = new Date().getTime() + suffix // 为文件命名

    const token =  window.location.href.indexOf('/prd') === -1 ?localStorage.getItem('token-llx-test'):localStorage.getItem('token-llx')

    http({
      method: 'post',
      url:  window.location.href.indexOf('/prd')===-1?'http://139.224.81.105:19999/qia-cloud-filesystem/OSS/companies/getStsToken':'http://139.224.81.105:9999/qia-cloud-filesystem/OSS/companies/getStsToken',
      headers:  { 'Authorization': 'Bearer ' + token}
    }).then(res => {
      const fileData = res
      var bucket = 'middle-file'
      var region = 'oss-cn-shanghai'
      var type = ''
      const client = new OSS({
        region,
        accessKeyId: fileData.accessKeyId,
        accessKeySecret: fileData.accessKeySecret,
        stsToken: fileData.stsToken,
        bucket
      })
      type = 'audio'
      client.multipartUpload(type + '/' + filename, file.file).then((result) => {
        var url = result.res.requestUrls[0]
        var length = url.lastIndexOf('?')
        var getUrl = length > 0 ? url.substr(0, length) : url // 文件最终路径
        this.setState({
          newAudioUrl:getUrl
        })
      }).catch(function(err) {
        notification.error({
          description:'上传失败',
          duration:1
        })
      })
  }).catch(err=>{
    notification.error({
      description:'上传失败',
      duration:1
    })
  })
  }
  
  // 播放
  playAudio = () => {

  if(this.state.isPlay) {
    this.setState({
      isPlay:false
     },()=>{
      this.audio.current.pause()
     })
     return
  }

   this.setState({
    audioUrl:this.state.fileList[0].url,
    isPlay:true
   },()=>{
    this.audio.current.play()
   })
  }
  // 音频结束
  audioEnd = () => {
    this.setState({
      isPlay:false
     })
  }
  // 删除音频
  removeAudio = () => {
    this.setState({
      fileList:[]
    },()=>{
      this.props.setAudio('')
    })

  }
  // 下载音频
  downloadAudio = () => {
    window.open(this.state.fileList[0].url)
  }
  // 替换音频
  replaceSong = () => {
    const _this = this
    confirm({
      title: '是否替换该音频',
      icon: <ExclamationCircleOutlined />,
      okText:"替换",
      cancelText:'取消',
      onOk() {
       _this.setState({
        checkVisible:true
       })
      },
      onCancel() {
      },
    });
  }
  // 确认替换
  handleOkFn = async() => {
    const _this = this
    if(!this.state.newAudioUrl) {
      message.error('请上传替换的音频');
      return
    }
    try{
      await replaceAudio({
        id:window.location.href.slice(window.location.href.indexOf('id=')+3),
        audioUrl: _this.state.newAudioUrl,
        audioUrlOld: _this.state.fileList[0].url
      })
      message.success('替换成功');
      _this.setState({
        checkVisible:false,
        audioUrlOld:''
      })
      this.props.updateInfo()
     } catch(err){
      message.error('替换失败，请重试');
     }
  }
    render() {
     const { fileList , isPlay, audioUrl,disabled} = this.state;


     return (
      <div className='audio-upload'>
        <Upload
          name='file'
          action="#"
          accept="audio/*"
          fileList={fileList}
          onChange={this.handleChange}
          onRemove={this.handleMove}
          customRequest={this.customRequest}
          maxCount={1}
          showUploadList={false}
        >
          <Button disabled={disabled} type='primary' icon={<UploadOutlined />}>上传音频</Button>
        </Upload>

        {
          fileList.length===1?<div>

          {!isPlay?<PlayCircleOutlined className='icon' onClick={this.playAudio}/>:<PauseCircleOutlined onClick={this.playAudio} className='icon' />}
          
           <DownloadOutlined className='icon' onClick={this.downloadAudio}/>

           {
             !disabled?<DeleteOutlined className='icon' onClick={this.removeAudio}/>:''
           }

           {
             window.location.href.indexOf('/word/wordInfo')!==-1&&!disabled&&this.props.userBtnRole.includes('WORD_RELACE')?<SwapOutlined className='icon' onClick={this.replaceSong}/>:''
           }

          <audio ref={this.audio} src={audioUrl} onEnded={this.audioEnd}></audio>

          </div>:''
        }
       

       <Modal
          width={500}
          visible={this.state.checkVisible}
          title={'替换音频'}
          onOk={this.handleOkFn}
          onCancel={this.handleCancel}
        >
           <Alert className="edit-alert" message='请上传替换的音频，此操作不可撤' type="success" />
          <Row>
            <Col span={8}></Col>
            <Col span={15}>
             <Upload
                name='file'
                action="#"
                accept="audio/*"
                fileList={fileList}
                customRequest={this.customRequestReplace}
                maxCount={1}
                showUploadList={false}
              >
                <Button type='primary' icon={<UploadOutlined />}>上传音频</Button>
              </Upload>

              {this.state.newAudioUrl?'上传成功':''}
            </Col>
            <Col span={1}></Col>
          </Row>
        </Modal>
       
      </div>
    );
  }
}

export default connect(state=>{
  return {
    userBtnRole:state.userBtnRole
  }
})(App);